package it.trekker.activities;

import java.util.List;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import it.trekker.R;
import it.trekker.dataexchange.PoiRealTimeInfo;
import it.trekker.db.GPSCoordinate;
import it.trekker.db.Poi;
import it.trekker.db.PoiDAO;
import it.trekker.gps.GPSLocationListenerMap;
import it.trekker.gps.TrackListener;
import it.trekker.map.MyItemizedOverlay;
import it.trekker.statistics.PoiDistanceStatistics;
import it.trekker.statistics.RealTimeStatistics;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import it.trekker.dialogs.PoiFriendlyNameDialog;

public class RealTimeMapActivity extends MapActivity implements LocationListener, PoiFriendlyNameDialog.INewPoi {

	private static final String TAG = RealTimeMapActivity.class.getSimpleName();
	private MapView mapView = null;
	private ImageButton addPoi_bt = null;
	private MapController mapController = null;
	private LocationManager locationManager = null;
	private GPSLocationListenerMap locationListener = null;

	private List<Overlay> mapOverlays;
	private Drawable marker;
	private MyItemizedOverlay climberItemizedOverlay;
	//	private PathOverlayManager pathOverlayManager = null;

	private Location mostRecentLocation = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.map_layout);

		addPoi_bt = (ImageButton) findViewById(R.id.add_poi);
		addPoi_bt.setVisibility(View.VISIBLE);
		addPoi_bt.setOnClickListener(new AddPoiListener());
		addPoi_bt.getBackground().setAlpha(75);

		mapView = (MapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);

		mapController = mapView.getController();

		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		String bestProvider = locationManager.getBestProvider(criteria, true);
		//		String bestProvider = locationManager.GPS_PROVIDER;
		mostRecentLocation = locationManager.getLastKnownLocation(bestProvider);

		Toast.makeText(this, "Best provider: " + bestProvider, Toast.LENGTH_SHORT).show();

		mapOverlays = mapView.getOverlays();

		//		pathOverlayManager = new PathOverlayManager(this, mapOverlays, mapView.getProjection());

		marker = this.getResources().getDrawable(R.drawable.climber_icon);
		climberItemizedOverlay = new MyItemizedOverlay(marker);
		mapOverlays.add(climberItemizedOverlay);

//		locationListener = new GPSLocationListenerMap();
//		locationListener.addListener(this);
//		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 2, locationListener);
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 2, this);

	}

	@Override
	protected void onResume() {
		super.onResume();

		if(mostRecentLocation != null) {
			GeoPoint geoPoint = location2GeoPoint(mostRecentLocation);
			climberItemizedOverlay.addItem(geoPoint, "Here", "Here");
			mapController.animateTo(geoPoint);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

//		locationListener.removeListener(this);
//		locationManager.removeUpdates(locationListener);
		locationManager.removeUpdates(this);
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	// Back key pression handled by the parent (ExcursionMainActivity tabactivity)
	@Override 
	public void onBackPressed() { 
		this.getParent().onBackPressed();
	}

	//	@Override
	//	public void onConfigurationChanged(Configuration newConfig) {
	//		super.onConfigurationChanged(newConfig);
	//	}





	//*************************************************************//
	//********************* Utility functions *********************//
	//*************************************************************//

	public void updateLocation(Location location) {

		mostRecentLocation = location;

		GeoPoint currentGeoPoint = location2GeoPoint(location);

		//		pathOverlayManager.addPoint(currentGeoPoint);		
		climberItemizedOverlay.setItem(currentGeoPoint, "Here", "Here");

		mapController.animateTo(currentGeoPoint);

	}	

	private GeoPoint location2GeoPoint(Location location) {

		Double latitude = location.getLatitude();
		Double longitude = location.getLongitude();
		int latE6 = Double.valueOf(latitude * 1E6).intValue();
		int longE6 = Double.valueOf(longitude * 1E6).intValue();

		return new GeoPoint(latE6, longE6);
	}






	//***********************************************************//
	//*********************** Option Menu ***********************//
	//***********************************************************//


	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.clear();
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.map_menu, menu);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {

		case R.id.map_mode_view:
			if(!mapView.isSatellite())
				mapView.setSatellite(true);
			else {
				mapView.setSatellite(false);
			}
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}





	//***********************************************************//
	//************************* Dialogs *************************//
	//***********************************************************//


	private static final int DIALOG_NEWPOI = 0;

	private void showNewPoiDialog() {
		showDialog(DIALOG_NEWPOI);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog;

		switch(id) {
		case DIALOG_NEWPOI:
			dialog = createNewPoiDialog();
			break;

		default:
			dialog = null;
		}

		return dialog;
	}

	private PoiFriendlyNameDialog createNewPoiDialog() {
		return new PoiFriendlyNameDialog(this);
	}





	//****************************************************************//
	//*********************** Listener classes ***********************//
	//****************************************************************//

	private class AddPoiListener implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			showDialog(DIALOG_NEWPOI);
		}

	}





	//*****************************************************************//
	//******** PoiFriendlyNameDialog.INewPoi interface methods ********//
	//*****************************************************************//

	@Override
	public Context getContext() {
		return this;
	}

	@Override
	public boolean createNewPoi(String friendlyName) {
		GPSCoordinate coord = new GPSCoordinate(mostRecentLocation);

		Poi poi = new Poi();
		poi.setExcursionId(RealTimeStatistics.getSharedInstance().getExcursionId());
		poi.setLocation(coord);
		poi.setFriendlyName(friendlyName);

		PoiDAO poiDAO = new PoiDAO(RealTimeMapActivity.this);
		poiDAO.open();
		poi.setId(poiDAO.insertPoi(poi));
		poiDAO.close();
		
		PoiRealTimeInfo info = new PoiRealTimeInfo();
		info.setPoi(poi);
		info.setDistanceToGoal(0);
		info.setMeanPace(RealTimeStatistics.getSharedInstance().getMeanPace());
		PoiDistanceStatistics.getSharedInstance().addPoi(info);
		
		Toast.makeText(this, "POI added", Toast.LENGTH_LONG).show();
		
		return true;
	}

	
	
	
	//******************************************************************//
	//*************** LocationListener interface methods ***************//
	//******************************************************************//
	
	
	@Override
	public void onLocationChanged(Location location) {
		updateLocation(location);
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
}
